# @Time : 2024-11-11 15:57
# @Author : Fioman 
# @Phone : 13149920693
"""
Eap配置相关,以及需要的一些中间变量
"""
import threading
import uuid
from datetime import datetime

from app.device_state import DeviceState
from db_tool.db_config import TableName
from db_tool.db_handler import DbHandler
from eap_control.eap_logger import EapLogger
from personal_tool.enum_data import EqpStatus

eapLogger = EapLogger()
db = DbHandler()


class EapConfig:
    """
    Eap配置相关,比如id,ip和port,呼叫Eap间隔,机台连线模式,Cim Mode机台操作模式,中间用到的一切变量
    都使用这文件进行中转,设置为单例模式.
    """
    __instance__ = None
    __initFlag__ = False
    __lock__ = threading.Lock()
    TimeOut = "TimeOut"
    ZmcRs = "传输控制器急停"
    RasterTrigger = "机械手光栅被挡"
    VacuoAlarm = "吸盘真空报警"
    CameraDisConn = "相机未连接异常"
    lastEqpStatus = EqpStatus.Stop

    def __new__(cls, *args, **kwargs):
        with  cls.__lock__:
            if cls.__instance__ is None:
                cls.__instance__ = super().__new__(cls, *args, **kwargs)
            return cls.__instance__

    def __init__(self):
        if not self.__initFlag__:
            eapLogger.print_and_debug("EapConifg._init__()初始化")
            self.operation_mode = None
            self.reload_eap_config_params()
            self.eapOnline = False
            self.border_thickness = 1.5
            self.copper_thickness = 1
            self.copper_area = 0
            self.process_name = "lotid"  # 批次ID
            self.pn_name = "recipeName"  # 料号
            self.panel_id = "panelId"  # 板子Id
            self.__initFlag__ = True

    def reload_eap_config_params(self):
        """
        从数据库中重新加载Eap配置相关的参数
        :return:
        """
        result = db.get_data_one(TableName.eapConfigParams, {"key": "1"})
        if not result.state:
            eapLogger.print_and_debug(result.data)
        else:
            self.eapOnline = False
            self.user_id = result.data.get("user_id", "")
            self.user_no = result.data.get("user_no", "")
            self.server_ip = result.data.get("server_ip", "")
            self.ask_duration = result.data.get("ask_duration", 60)
            self.time_report_duration = result.data.get("time_report_duration", 60 * 60)
            self.wip_count_duration = result.data.get("wip_count_duration", 60)  # 上报设备内产品数量
            self.request_url_base = result.data.get("request_url_base", "")
            self.pcIp = result.data.get("pc_ip", "0.0.0")
            self.pcPort = result.data.get("pc_port", 8028)
            self.lineCleaning = "1"  # 1 清线完成   2 清线失败
            self.moveSpeed = result.data.get("move_speed", "500")
            self.backSpeed = result.data.get("back_speed", "500")
            self.robotWorkSpeed = result.data.get("robot_work_speed", "1000")
            self.moveSpeed = f"{self.moveSpeed} mm/sec"
            self.backSpeed = f"{self.backSpeed} mm/sec"
            self.robotWorkSpeed = f"{self.robotWorkSpeed} mm/sec"
            operation_mode = result.data.get("operation_mode", "自动模式")
            if self.operation_mode is not None and operation_mode != self.operation_mode:
                opToEap = self.get_operation_mode_code(operation_mode)
                # 操作模式发生了改变
                from eap_control import eap_request
                ds = DeviceState()
                eap_request.request_equipment_information(opToEap, ds.orderUsedId, self.lineCleaning)
            self.operation_mode = operation_mode
            eapLogger.print_and_debug(
                f"eap参数加载成功: result={result.data}\n"
            )

    def get_operation_mode_code(self, operation_mode):
        """
        通过operation_mode 获取其数字代码形式:
        0: 手动模式[Manual]: 不上报资料给EAP
        1: 自动模式[Auto]: 上报数据, 并接受EAP的数据
        2: 半自动模式[Semi-Auto]: 上报数据, 但在设备上设定数据
        :param self:
        :param operation_mode:
        :return:
        """
        modeMapping = {
            "手动模式": "0",
            "自动模式": "1",
            "半自动模式": "2"
        }
        return modeMapping.get(operation_mode, "1")

    @staticmethod
    def get_eap_params_from_web():
        """
        web获取Eap的配置参数内容
        @return:
        """
        return db.get_data_list(TableName.eapConfigParams)

    def save_eap_params_from_web(self, eap_config_prams):
        """
        web界面上点击了保存eap参数的按钮
        @return:
        """
        result = db.update_data(TableName.eapConfigParams, {"key": "1"}, eap_config_prams)
        if result.state:
            self.reload_eap_config_params()
        return result

    @staticmethod
    def get_uuid():
        return str(uuid.uuid4())

    @staticmethod
    def get_now():
        """
        获取时间,格式为2024-08-09 14:13:37
        @return:
        """
        return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    @staticmethod
    def get_request_header(messageName):
        """
        获取请求的消息头
        """
        return {
            "messagename": messageName,
            "timestamp": datetime.now().strftime("%Y%m%d%H%M%S%f"),  # 获取带有ms的格式
            "from": "EQP",
            "to": "EAP",
            "token": "8e39cb39f7bc11eab31a00505696508c"
        }

    def update_eap_status(self, eqpStatus: EqpStatus):
        """
        更新eqp的状态
        :param eqpStatus:
        :return:
        """
        if eqpStatus != EapConfig.lastEqpStatus:
            eapLogger.print_and_debug(f"检测到设备状态发生改变,上报到Eap,状态从 {EapConfig.lastEqpStatus.name} 变成 {eqpStatus.name}")
            EapConfig.lastEqpStatus = eqpStatus
            from eap_control import eap_request, resp_parse
            response = eap_request.request_equipment_status(eqpStatus.value)
            resp_parse.parse_equipment_status_response("EquipmentStatus", response)

    def process_data_report(self, report_type: str, judge: str):
        """
        上报单片数据
        :param report_type:
        :param judge:
        :return:
        """
        from eap_control import eap_request
        proc_data_list = {
            "proc_data": [
                {
                    "data_no": "1",
                    "data_value": str(self.border_thickness),
                    "data_item": " Border Thickness"
                },
                {
                    "data_no": "2",
                    "data_value": self.copper_thickness,
                    "data_item": " Copper Thickness    "
                },
                {
                    "data_no": "3",
                    "data_value": str(self.copper_area),
                    "data_item": " Copper Area   "
                },
            ]
        }
        response = eap_request.request_process_data_report(report_type, judge, self.process_name, self.pn_name, self.panel_id, proc_data_list)
        return response
